/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-4-14 下午10:18 Created by dwzhang
 */
package com.jade.framework.base.lang;

import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.reflect.ConstructorUtils;
import org.apache.commons.lang3.reflect.MethodUtils;

/**
 * JAVA Reflection工具类。
 *
 * @author dwzhang
 * @version 1.0 13-4-14 下午10:18
 */
public class ReflectUtils
{
    public static <T> T newInstance(String className, java.lang.Object... args)
    {
        Class clazz = internalLoadClass(className);
        return (T)newInstance(clazz, args);
    }

    public static <T> T newInstance(Class<T> clazz, java.lang.Object... args)
    {
        //查找getInstance方法，如果存在调用之
        try {
            return (T)ConstructorUtils.invokeConstructor(clazz, args);
        }
        catch (Exception ex) {
            throw new IllegalArgumentException("Invalid class name " + clazz.getName(), ex);
        }
    }

    /**
     * 构建单例对象
     *
     * @param className 类名
     * @return 对象
     */
    public static final Object newSingleton(String className)
    {
        Class clazz = internalLoadClass(className);
        return newSingleton(clazz);
    }

    /**
     * 构建单例对象
     *
     * @param clazz 类
     * @return 对象
     */
    public static <T> T newSingleton(Class<T> clazz)
    {
        //查找getInstance方法，如果存在调用之
        try {
            return (T)MethodUtils.invokeStaticMethod(clazz, "getInstance");
        }
        catch (Exception ex) {
            // do nothing
        }
        return (T)newInstance(clazz);
    }

    /**
     * 内部装载类
     *
     * @param className 类名.
     */
    static final Class<?> internalLoadClass(String className)
    {
        try {
            return ClassUtils.getClass(ClassLoaderUtils.getClassLoader(), className);
        }
        catch (ClassNotFoundException ex) {
            throw new IllegalArgumentException("Invalid class name " + className, ex);
        }
    }
}
